/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.gm.controller;

import com.icee.myth.gm.GmServer;
import com.icee.myth.gm.channelhandler.HttpServerHandler;
import com.icee.myth.gm.client.GameServerClient;
import com.icee.myth.gm.db.DbHandler;
import com.icee.myth.gm.player.PlayerInfo;
import com.icee.myth.protobuf.ExternalCommonProtocol.MailContentProto;
import com.icee.myth.protobuf.ExternalCommonProtocol.RewardProto;
import com.icee.myth.protobuf.ExternalCommonProtocol.RewardItemProto;
import com.icee.myth.utils.Consts;
import com.icee.myth.utils.Escape;
import com.icee.myth.utils.JSONHelper;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;

/**
 *
 * @author liuxianke
 */
public class MailController extends AbstractController {

    public MailController(int privilege) {
        super(privilege);
    }

    @Override
    public void process() {
        // 注意：将数据库表中只记录操作号、操作员、操作类型以及收到的json格式数据，其他列删除        
        Long serverId = (Long)jobj.get("server");
        String title = Escape.unescape((String)jobj.get("title"));
        String description = Escape.unescape((String)jobj.get("description"));
        List<String> targetList = (List<String>)jobj.get("targets");
        String targetCid = (String)jobj.get("targetCid");
        List<JSONObject> rewardObjList = (List<JSONObject>)jobj.get("reward");
        
        if ((title != null) && (description != null) && (serverId != null)) {
            MailContentProto.Builder builder1 = MailContentProto.newBuilder();
            builder1.setTitle(title);
            builder1.setDescription(description);

            if ((rewardObjList != null) && !rewardObjList.isEmpty()) {
                if ((userData.privilege & Consts.PRIVILEGE_MODIFY) == 0) {
                    HttpServerHandler.sendErrorNoPrivilege(request, e);
                    return ;
                 }

                int gold = 0;
                int silver = 0;
                int experience = 0;
                int energy = 0;

                RewardProto.Builder builder2 = RewardProto.newBuilder();
                for (JSONObject rewardObj : rewardObjList) {
                    String rewardType = (String)rewardObj.get("type");
                    if (rewardType.compareTo("gold") == 0) {
                        gold += (int)(long)(Long)rewardObj.get("num");
                    } else if (rewardType.compareTo("silver") == 0) {
                        silver += (int)(long)(Long)rewardObj.get("num");
                    } else if (rewardType.compareTo("experience") == 0) {
                        experience += (int)(long)(Long)rewardObj.get("num");
                    } else if (rewardType.compareTo("energy") == 0) {
                        energy += (int)(long)(Long)rewardObj.get("num");
                    } else if (rewardType.compareTo("card") == 0) {
                        RewardItemProto.Builder builder3 = RewardItemProto.newBuilder();

                        builder3.setType(Consts.REWARD_ITEM_TYPE_CARD);
                        builder3.setId((int)(long)(Long)rewardObj.get("id"));
                        builder3.setLevel((int)(long)(Long)rewardObj.get("level"));
                        builder3.setNum((int)(long)(Long)rewardObj.get("num"));

                        builder2.addItems(builder3);
                    } else if (rewardType.compareTo("item") == 0) {
                        RewardItemProto.Builder builder3 = RewardItemProto.newBuilder();

                        builder3.setType(Consts.REWARD_ITEM_TYPE_ITEM);
                        builder3.setId((int)(long)(Long)rewardObj.get("id"));
                        builder3.setNum((int)(long)(Long)rewardObj.get("num"));

                        builder2.addItems(builder3);
                    }
                }

                if (gold > 0) {
                    builder2.setGold(gold);
                }

                if (silver > 0) {
                    builder2.setSilver(silver);
                }

                if (experience > 0) {
                    builder2.setExperience(experience);
                }

                if (energy > 0) {
                    builder2.setEnergy(energy);
                }

                builder1.setReward(builder2);
            }
            
            MailContentProto mailContentProto = builder1.build();

            if (serverId >= 0) {
                GameServerClient gameServerClient = GmServer.INSTANCE.getServer(serverId.intValue());

                if (gameServerClient != null) {
                    if ((targetList != null) && !targetList.isEmpty()) {
                        ArrayList<String> errpassportList = new ArrayList<String>();
                        DbHandler managerDbHandler = new DbHandler(GmServer.INSTANCE.managerDbHost, GmServer.INSTANCE.managerDbName);
                        for (String targetPassport : targetList) {
                            PlayerInfo playerInfo = managerDbHandler.getPlayerInfoFromDB(targetPassport);

                            if (playerInfo != null) {
                                if (gameServerClient.addMail(playerInfo.cid, mailContentProto)) {
                                    MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, "Add mail to passport[" + targetPassport + "] user [" + playerInfo.cid + "] in server["+gameServerClient.serverConfig.id+"]");
                                } else {
                                    errpassportList.add(targetPassport);
                                    MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Fail to add mail to passport[" + targetPassport + "] user [" + playerInfo.cid + "] in server["+gameServerClient.serverConfig.id+"]");
                                }
                            } else {
                                errpassportList.add(targetPassport);
                            }
                        }
                        managerDbHandler.close();

                        // 需返回客户端失败的列表
                        dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_MAIL, jobj.toJSONString());
                        HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0,\"passports\":" + JSONHelper.toJSON(errpassportList) + "}", null);
                    } else if (targetCid != null) {                        
                        if (gameServerClient.addMail(Integer.parseInt(targetCid), mailContentProto)) {
                            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, "Add mail to user [" + targetCid + "] in server["+gameServerClient.serverConfig.id+"]");
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0}", null);
                        } else {
                            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Fail to add mail to user [" + targetCid + "] in server["+gameServerClient.serverConfig.id+"]");
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1}", null);
                        }
                    } else {
                        if (gameServerClient.addMail(Consts.ALL_PLAYER_ID, mailContentProto)) {
                            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, "Add mail to all users in server["+gameServerClient.serverConfig.id+"]");

                            dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_MAIL, jobj.toJSONString());
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0}", null);
                        } else {
                            MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Fail to add mail to all players in server["+gameServerClient.serverConfig.id+"]");
                            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"send mail to all players in server["+gameServerClient.serverConfig.id+"] failed\"}", null);
                        }
                    }
                } else {
                    HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"server " + serverId + " not found\"}", null);
                }
            } else {
                ArrayList<Integer> errServerList = new ArrayList<Integer>();

                for(GameServerClient gameServerClient : GmServer.INSTANCE.getGameServerClients().values()){
                    if (gameServerClient.addMail(Consts.ALL_PLAYER_ID, mailContentProto)) {
                        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, "Add mail to all users in server["+gameServerClient.serverConfig.id+"]");
                    } else {
                        errServerList.add(gameServerClient.getId());
                        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Fail to add mail to all users in server["+gameServerClient.serverConfig.id+"]");
                    }
                }
                dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_MAIL, jobj.toJSONString());
                HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0,\"servers\":" + JSONHelper.toJSON(errServerList) + "}", null);
            }
        } else {
            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"param error\"}", null);
        }
    }
}
